package com.feifan.monthhelper.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feifan.monthhelper.R;
import com.feifan.monthhelper.bean.db.DayRecordBean;
import com.feifan.monthhelper.bean.db.LivingHabitBean;
import com.feifan.monthhelper.bean.db.MenstrualRecordBean;
import com.feifan.monthhelper.calculate.CalculateUtils;
import com.feifan.monthhelper.calendar.CalendarUtils;
import com.feifan.monthhelper.constant.Constant;
import com.feifan.monthhelper.db.DBUtls;
import com.feifan.monthhelper.ui.adapter.LoveProtectAdapter;
import com.feifan.monthhelper.ui.base.BaseActivity;
import com.feifan.monthhelper.ui.guide.Step1Activity;
import com.feifan.monthhelper.utils.CommonDialogUtils;
import com.feifan.monthhelper.utils.DateUtils;
import com.feifan.monthhelper.utils.NumberUtils;
import com.feifan.monthhelper.utils.SPUtils;
import com.feifan.monthhelper.wedget.DoubleClickListener;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.qqtheme.framework.picker.OptionPicker;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {

    @BindView(R.id.rl_title)
    LinearLayout rlTitle;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_mine)
    TextView tvMine;
    @BindView(R.id.calendarView)
    CalendarView calendarView;
    @BindView(R.id.iv_show_menstruation)
    ImageView ivShowMenstruation;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.tv_hot_water)
    TextView tvHotWater;
    @BindView(R.id.tv_eat_fruit)
    TextView tvEatFruit;
    @BindView(R.id.tv_take_exercise)
    TextView tvTakeExercise;
    @BindView(R.id.tv_eat_breakfast)
    TextView tvEatBreakfast;
    @BindView(R.id.tv_defecate)
    TextView tvDefecate;
    @BindView(R.id.ratingBar_menstrual_blood)
    RatingBar ratingBarMenstrualBlood;
    @BindView(R.id.ratingBar_keenly_feel)
    RatingBar ratingBarKeenlyFeel;
    @BindView(R.id.rv_love_protect)
    RecyclerView rvLoveProtect;

    private LoveProtectAdapter loveProtectAdapter;
    LivingHabitBean livingHabitBean;
    private List<DayRecordBean> dayRecordBeans;
    private int dayOfMonth;
    private Date selectDate;
    String menstrual;
    int menstrual_period;
    int span_period;
    //重置数据
    boolean resetData;

    //爱爱措施选择
    private OptionPicker.OnOptionPickListener lovePickListener = new OptionPicker.OnOptionPickListener() {
        @Override
        public void onOptionPicked(int index, String item) {
//            SPUtils.getInstance().put(Constant.ShareKey.ALARM_TIME, item);
            List<String> adapterProtects = loveProtectAdapter.getProtects();
            if (adapterProtects == null) {
                adapterProtects = new ArrayList<>();
            }
            adapterProtects.add(item);
            List<String> protects = new ArrayList<>(adapterProtects);
            loveProtectAdapter.notifyDataSetChanged();

            if (dayRecordBeans != null && dayRecordBeans.size() >= dayOfMonth) {
                DayRecordBean dayRecordBean = dayRecordBeans.get(dayOfMonth - 1);
                dayRecordBean.protects = protects;
                DBUtls.insertDayRecord(dayRecordBean);
                LogUtils.d("db data : ", dayRecordBean);
//                Date date = CalendarAlarmUtils.getSelectedDate(calendarView);
//                LoveProtectBean loveProtectBean = new LoveProtectBean(date, protects)
//                DBUtls.updateLoveProtect(loveProtectBean);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (StringUtils.isEmpty(SPUtils.getInstance().getString(Constant.ShareKey.BIRTHDAY))) {
            startActivity(new Intent(getApplication(), Step1Activity.class));
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public View getTitleView() {
        return rlTitle;
    }

    @Override
    protected void initData() {
        dayOfMonth = calendarView.getCurDay();
        selectDate = CalendarUtils.getSelectedDate(calendarView);
//        Map<String, Calendar> calendarMap = CalculateUtils.caculateDateMap(DateUtils.init().StringToDate(menstrual, DateUtils.DateStyle.YYYY_MM_DD), menstrual_period, span_period);
//        calendarView.addSchemeDate(calendarMap);

        loveProtectAdapter = new LoveProtectAdapter();

    }

    @Override
    protected void initView() {

        calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @Override
            public void onMonthChange(int year, int month) {
                //设置selectDate为下一个月1号，
                java.util.Calendar calendar = java.util.Calendar.getInstance();
                calendar.set(java.util.Calendar.YEAR, year);
                calendar.set(java.util.Calendar.MONTH, month - 1);
                calendar.set(java.util.Calendar.DAY_OF_MONTH, 1);
                calendar.get(java.util.Calendar.DAY_OF_MONTH);
                selectDate = calendar.getTime();

                loadDataFromDb();
                LogUtils.d("onMonthChange : ", "selectDate = " + DateUtils.init().dateToString(selectDate, DateUtils.DateStyle.YYYY_MM_DD));
                LogUtils.d("onMonthChange : ", "year = " + year + "- month" + month);

            }
        });
        calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                initTitleDate(calendar);
                selectDate = CalendarUtils.getSelectedDate(calendarView);
                dayOfMonth = calendar.getDay();
                LogUtils.d("calendar : ", "calendar = " + calendar.getMonth() + "-" + calendar.getDay() + " -- isClick =" + isClick);

                initRatingBar();
//                insertCalculateData();
//                CalculateUtils.calculateAndSaveToDb();
            }
        });

        tvMine.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                Intent intent = new Intent(getApplication(), MineActivity.class);
                startActivityForResult(intent, Constant.ConstantCode.REQUEST_MINE);

                List<DayRecordBean> livingHabitDaos = DBUtls.getAllDayRecord();
                for (DayRecordBean livingHabitBean : livingHabitDaos) {
                    LogUtils.d("db data : ", livingHabitBean == null, GsonUtils.toJson(livingHabitBean));
                }
            }
        });
        ivAdd.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                List<String> loves = Arrays.asList(getResources().getStringArray(R.array.love_choice_strings));
                CommonDialogUtils.ShowOptionPicker(MainActivity.this, "添加爱爱记录", loves, lovePickListener);
            }
        });

        tvHotWater.setOnClickListener(view -> {
            onLivingHabitClick(tvHotWater);
        });
        tvDefecate.setOnClickListener(view -> {
            onLivingHabitClick(tvDefecate);
        });
        tvEatBreakfast.setOnClickListener(view -> {
            onLivingHabitClick(tvEatBreakfast);
        });
        tvEatFruit.setOnClickListener(view -> {
            onLivingHabitClick(tvEatFruit);
        });
        tvTakeExercise.setOnClickListener(view -> {
            onLivingHabitClick(tvTakeExercise);
        });
        ivShowMenstruation.setOnClickListener(view -> {
            if(CalendarUtils.getDateSpan(new Date(calendarView.getSelectedCalendar().getTimeInMillis()), new Date()) < 0) {
                //当前日期大于今天日期，不允许操作
                ToastUtils.showShort(R.string.time_not_arrived);
                return;
            }
            view.setSelected(!view.isSelected());
            DayRecordBean dayRecordBean = dayRecordBeans.get(dayOfMonth - 1);

            String menstrual = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_START_DATE);
            String menstrual_cycle = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_DAYS);
            String menstrual_span = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_SPAN_DAYS);
            int menstrual_period = NumberUtils.StringToInt(menstrual_cycle.replaceAll("天", ""));
            int span_period = NumberUtils.StringToInt(menstrual_span.replaceAll("天", ""));

            Date selectedDate = CalendarUtils.getSelectedDate(calendarView);
            if (view.isSelected()) {
                //打开修改当前日期的状态
                dayRecordBean.state = Constant.MenstrualState.MENSTRUAL_DAY;

                MenstrualRecordBean menstrualRecordBean = DBUtls.queryMenstrualRecordNearBy(selectedDate);
                //插入新的周期记录
                if (menstrualRecordBean == null) {
                    menstrualRecordBean = new MenstrualRecordBean();
                    menstrualRecordBean.start_date = selectedDate;
                    menstrualRecordBean.end_date = CalculateUtils.addDate(selectedDate, menstrual_period - 1);
                    DBUtls.insertMenstrualRecord(menstrualRecordBean);

                    int size = menstrual_period;
                    List<DayRecordBean> dayRecordBeans = new ArrayList<>();
                    for (int i=0;i<size;i++) {
                        Date queryDate = CalculateUtils.addDate(menstrualRecordBean.start_date, i);
                        DayRecordBean dayRecordBean1 = DBUtls.loadByDate(queryDate);
                        if(dayRecordBean1 == null) {
                            dayRecordBean1 = new DayRecordBean();
                            dayRecordBean1.createDate = queryDate;
                        }
                        if(CalculateUtils.getDayCount(queryDate) > CalculateUtils.getDayCount(new Date())) {
                            dayRecordBean1.state = Constant.MenstrualState.CACULATE_MENSTRUAL_DAY;
                        } else {
                            dayRecordBean1.state = Constant.MenstrualState.MENSTRUAL_DAY;
                        }
                        dayRecordBeans.add(dayRecordBean1);
                    }
                    DBUtls.insertDayRecords(dayRecordBeans);
                } else {
                    int compare = menstrualRecordBean.start_date.compareTo(selectedDate);
                    if (compare > 0) {
                        DBUtls.deleteMenstrualRecord(menstrualRecordBean);
                        menstrualRecordBean.start_date = selectedDate;
                    } else if (selectedDate.compareTo(menstrualRecordBean.end_date) > 0) {
                        DBUtls.deleteMenstrualRecord(menstrualRecordBean);
                        menstrualRecordBean.end_date = selectedDate;
                    }
                    DBUtls.insertMenstrualRecord(menstrualRecordBean);
                }

                //更新前续的数据
                updateBeforeData(menstrual_period, span_period, menstrualRecordBean);

                //更新周期后面数据
                updateAfterData(menstrual_period, span_period, menstrualRecordBean);

                ratingBarKeenlyFeel.setIsIndicator(false);
                ratingBarMenstrualBlood.setIsIndicator(false);
                updateCalendarView(dayRecordBean);
                loadDataFromDb();
            } else {
                MenstrualRecordBean menstrualRecordBean = DBUtls.queryMenstrualRecordBy(selectedDate);
                //取消重新计算当前日期的预测
//                dayRecordBean = CalculateUtils.caculateDayRecordBean(DateUtils.init().StringToDate(menstrual, DateUtils.DateStyle.YYYY_MM_DD), menstrual_period, span_period, dayRecordBean);
                //更新月经记录表数据
                if (menstrualRecordBean != null) {
                    if (menstrualRecordBean.start_date.compareTo(selectedDate) == 0) {
                        if (menstrualRecordBean.end_date.compareTo(selectedDate) == 0) {
                            DBUtls.deleteMenstrualRecord(menstrualRecordBean);
                        } else {
//                            updateDayRecord(selectedDate);
                            dayRecordBean.state = Constant.MenstrualState.SAFE_DAY;
                            //开始日期后移一天
                            menstrualRecordBean.start_date = CalculateUtils.addDate(menstrualRecordBean.start_date, 1);
                            DBUtls.insertMenstrualRecord(menstrualRecordBean);

                            //更新前续的数据
                            updateBeforeData(menstrual_period, span_period, menstrualRecordBean);
                        }
                    } else if (menstrualRecordBean.end_date.compareTo(selectedDate) == 0) {
//                        updateDayRecord(selectedDate);
                        dayRecordBean.state = Constant.MenstrualState.SAFE_DAY;
                        //结束日期前移一天
                        menstrualRecordBean.end_date = CalculateUtils.addDate(menstrualRecordBean.end_date, -1);
                        DBUtls.insertMenstrualRecord(menstrualRecordBean);

                        //更新周期后面数据
                        updateAfterData(menstrual_period, span_period, menstrualRecordBean);
                    } else {
                        Date endDate = menstrualRecordBean.end_date;
                        menstrualRecordBean.end_date = CalculateUtils.caculateOffsetDate(DateUtils.init().StringToDate(menstrual, DateUtils.DateStyle.YYYY_MM_DD), menstrual_period, span_period, selectedDate, -1);
                        DBUtls.insertMenstrualRecord(menstrualRecordBean);

                        menstrualRecordBean.end_date = endDate;
                        menstrualRecordBean.start_date = CalculateUtils.caculateOffsetDate(DateUtils.init().StringToDate(menstrual, DateUtils.DateStyle.YYYY_MM_DD), menstrual_period, span_period, selectedDate, 1);
                        DBUtls.insertMenstrualRecord(menstrualRecordBean);
                    }
                }

                //月经关闭，月经相关状态恢复0
                dayRecordBean.pain_level = 0;
                dayRecordBean.blood_level = 0;
                ratingBarKeenlyFeel.setIsIndicator(true);
                ratingBarMenstrualBlood.setIsIndicator(true);
                loadDataFromDb();
//                updateCalendarView(dayRecordBean);
            }
            initRatingBar();
            calendarView.postInvalidate();
            DBUtls.insertDayRecord(dayRecordBean);
        });

        ratingBarKeenlyFeel.setOnRatingBarChangeListener((ratingBar, v, b) -> {
            //更新痛感数据
            if (dayRecordBeans != null && dayRecordBeans.size() >= dayOfMonth && !resetData) {
                DayRecordBean dayRecordBean = dayRecordBeans.get(dayOfMonth - 1);
                dayRecordBean.pain_level = (int) v;
                DBUtls.insertDayRecord(dayRecordBean);
                LogUtils.d("db data : ", GsonUtils.toJson(dayRecordBean));
            }
//            PainBean painBean = new PainBean(CalendarAlarmUtils.getSelectedDate(calendarView), (int) v);
//            DBUtls.updatePainFeel(painBean);
        });

        ratingBarMenstrualBlood.setOnRatingBarChangeListener((ratingBar, v, b) -> {
            //更新经期流量数据
            if (dayRecordBeans != null && dayRecordBeans.size() >= dayOfMonth && !resetData) {
                DayRecordBean dayRecordBean = dayRecordBeans.get(dayOfMonth - 1);
                dayRecordBean.blood_level = (int) v;
                DBUtls.insertDayRecord(dayRecordBean);
                LogUtils.d("db data : ", GsonUtils.toJson(dayRecordBean));
            }
//            MenstrualBloodBean painBean = new MenstrualBloodBean(CalendarAlarmUtils.getSelectedDate(calendarView), (int) v);
//            DBUtls.updateMenstrualBlood(painBean);
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvLoveProtect.setLayoutManager(layoutManager);
        rvLoveProtect.setAdapter(loveProtectAdapter);


        loadDataFromDb();
    }

    private void updateDayRecord(Date selectedDate) {
        DayRecordBean dayRecordBean = DBUtls.loadByDate(selectedDate);
        if (dayRecordBean == null) {
            dayRecordBean = new DayRecordBean();
            dayRecordBean.createDate = selectedDate;
        }
        dayRecordBean.state = Constant.MenstrualState.SAFE_DAY;
        DBUtls.insertDayRecord(dayRecordBean);
    }

    private void updateAfterData(int menstrual_period, int span_period, MenstrualRecordBean menstrualRecordBean) {
//        Date preDate;
        MenstrualRecordBean nextRecordBean = null;
        List<MenstrualRecordBean> menstrualRecordBeanList = DBUtls.queryAllMenstrualRecord();
        Collections.sort(menstrualRecordBeanList);
        for(int i=0;i<menstrualRecordBeanList.size();i++) {
            MenstrualRecordBean recordBean = menstrualRecordBeanList.get(i);
            if(recordBean.start_date.compareTo(menstrualRecordBean.start_date) == 0) {
                if(i > 0) {
                    nextRecordBean = menstrualRecordBeanList.get(i-1);
                }
//                if(i < menstrualRecordBeanList.size() - 1) {
//                    preDate = menstrualRecordBeanList.get(i+1).start_date;
//                }
            }
        }

        if(nextRecordBean == null) {
            //更新后续的数据
            List<DayRecordBean> dayRecordBeans2 = DBUtls.queryDayRecordFrom(CalculateUtils.addDate(menstrualRecordBean.start_date, 0));
            CalculateUtils.calculateFromAfterMenstrualDate(menstrualRecordBean.start_date, CalculateUtils.getDateSpan(menstrualRecordBean.end_date, menstrualRecordBean.start_date), menstrual_period, span_period, dayRecordBeans2);
            DBUtls.insertDayRecords(dayRecordBeans2);
        }
    }

    //更新前续的数据
    private void updateBeforeData(int menstrual_period, int span_period, MenstrualRecordBean menstrualRecordBean) {
        Date preDate = CalculateUtils.addDate(menstrualRecordBean.start_date, -span_period);
        List<MenstrualRecordBean> menstrualRecordBeanList = DBUtls.queryAllMenstrualRecord();
        Collections.sort(menstrualRecordBeanList);
        for(int i=0;i<menstrualRecordBeanList.size();i++) {
            MenstrualRecordBean recordBean = menstrualRecordBeanList.get(i);
            if(recordBean.start_date.compareTo(menstrualRecordBean.start_date) == 0) {
                if(i < menstrualRecordBeanList.size() - 1) {
                    preDate = menstrualRecordBeanList.get(i+1).start_date;
                }
            }
        }
        List<DayRecordBean> dayRecordBeans = DBUtls.queryDayRecordBy(preDate, menstrualRecordBean.start_date);
        CalculateUtils.calculateFrombeforeMenstrualDate(preDate, menstrualRecordBean.start_date, menstrual_period, span_period, dayRecordBeans);
        DBUtls.insertDayRecords(dayRecordBeans);
    }

    private void updateCalendarView(DayRecordBean dayRecordBean) {
        Calendar calendar = createCalendar(dayRecordBean);
        if (calendarMap.keySet().contains(calendar.toString())) {
            Calendar c = calendarMap.get(calendar.toString());
            if (c == null) c = calendar;
            setCalendarColor(dayRecordBean, c);
            calendarMap.put(c.toString(), c);
            calendarView.setSchemeDate(calendarMap);
        } else {
            setCalendarColor(dayRecordBean, calendar);
            calendarMap.put(calendar.toString(), calendar);
            calendarView.setSchemeDate(calendarMap);
        }
    }

    private void loadDataFromDb() {
        Disposable disposable = Observable.create((ObservableOnSubscribe<List<DayRecordBean>>) emitter -> {
            emitter.onNext(DBUtls.queryDayRecordBy(CalendarUtils.getFirtDayOfMonth(selectDate), CalendarUtils.getLastDayOfMonth(selectDate)));
            emitter.onComplete();
        })
                .doOnSubscribe(d -> showLoadingDialog("数据加载中..."))
                .doOnError(o -> dismisDialog())
                .doOnComplete(() -> dismisDialog())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    dayRecordBeans = o;
                    if (dayRecordBeans == null || dayRecordBeans.size() == 0) {
                        LogUtils.d("dayRecordBeans is null");
                    } else {
                        fillCalendarView(dayRecordBeans);
                        initRatingBar();
                    }
                });
        addDisposable(disposable);
    }

    Map<String, Calendar> calendarMap;

    //填充日历数据
    private void fillCalendarView(List<DayRecordBean> dayRecordBeans) {
        if (dayRecordBeans == null) return;

        for (DayRecordBean bean : dayRecordBeans) {
            LogUtils.d("fillCalendarView  " + DateUtils.init().dateToString(bean.createDate, DateUtils.DateStyle.YYYY_MM_DD));
            LogUtils.d("fillCalendarView  " + GsonUtils.toJson(bean));
        }

        if (calendarMap == null)
            calendarMap = new HashMap<>();
        for (DayRecordBean bean : dayRecordBeans) {
            if (bean.state == 0) continue;
            Calendar calendarBean = createCalendar(bean);
            setCalendarColor(bean, calendarBean);
            calendarMap.put(calendarBean.toString(), calendarBean);
        }
        calendarView.setSchemeDate(calendarMap);
        calendarView.postInvalidate();
    }

    private void setCalendarColor(DayRecordBean bean, Calendar calendarBean) {
        if (bean.state == Constant.MenstrualState.CACULATE_MENSTRUAL_DAY) {
            calendarBean.setSchemeColor(Constant.MenstrualColor.CACULATE_MENSTRUAL_DAY);
        } else if (bean.state == Constant.MenstrualState.MENSTRUAL_DAY) {
            calendarBean.setSchemeColor(Constant.MenstrualColor.MENSTRUAL_DAY);
        } else if (bean.state == Constant.MenstrualState.OVULATORY_DAY) {
            calendarBean.setSchemeColor(Constant.MenstrualColor.OVULATORY_DAY);
        } else if (bean.state == Constant.MenstrualState.SAFE_DAY) {
            calendarBean.setSchemeColor(Constant.MenstrualColor.SAFE_DAY);
        }
    }

    @NotNull
    private Calendar createCalendar(DayRecordBean bean) {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.clear();
        calendar.setTime(bean.createDate);
        Calendar calendarBean = new Calendar();
        calendarBean.setYear(calendar.get(java.util.Calendar.YEAR));
        calendarBean.setDay(calendar.get(java.util.Calendar.DAY_OF_MONTH));
        calendarBean.setMonth(calendar.get(java.util.Calendar.MONTH) + 1);
        return calendarBean;
    }

    private void initRatingBar() {
        resetData = true;
        ratingBarKeenlyFeel.setRating(0);
        ratingBarMenstrualBlood.setRating(0);
        ivShowMenstruation.setSelected(false);
        if (dayRecordBeans != null && dayRecordBeans.size() >= dayOfMonth) {
            DayRecordBean dayRecordBean = dayRecordBeans.get(dayOfMonth - 1);
            ratingBarMenstrualBlood.setRating(dayRecordBean.blood_level);
            ratingBarKeenlyFeel.setRating(dayRecordBean.pain_level);
            updateLivingHabitView(dayRecordBean);
            updateLoveProtectView(dayRecordBean);

            ivShowMenstruation.setSelected(dayRecordBean.state == Constant.MenstrualState.MENSTRUAL_DAY);
            if (ivShowMenstruation.isSelected()) {
                ratingBarKeenlyFeel.setIsIndicator(false);
                ratingBarMenstrualBlood.setIsIndicator(false);
            } else {
                ratingBarKeenlyFeel.setIsIndicator(true);
                ratingBarMenstrualBlood.setIsIndicator(true);
            }
            LogUtils.d("db data : ", GsonUtils.toJson(dayRecordBean));
        }
        resetData = false;
    }

    //计算并插入数据库
    private void insertCalculateData() {
        Disposable disposable = Observable.create(emitter -> {
            emitter.onNext(1);
            emitter.onComplete();
        })
                .doOnSubscribe(d -> showLoadingDialog("初始化数据..."))
                .doOnNext(o -> CalculateUtils.calculateAndSaveToDb())
                .doOnError(o -> dismisDialog())
                .doOnComplete(() -> dismisDialog())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    dayRecordBeans = DBUtls.queryDayRecordBy(CalendarUtils.getFirtDayOfMonth(selectDate), CalendarUtils.getLastDayOfMonth(selectDate));
                    fillCalendarView(dayRecordBeans);
                });
        addDisposable(disposable);
    }

    //生活习惯标签被点击
    private void onLivingHabitClick(TextView tvHotWater) {
        tvHotWater.setSelected(!tvHotWater.isSelected());
        updateLivingHabit(tvHotWater);
    }

    private void initTitleDate(Calendar calendar) {
        int currentDay = calendarView.getCurDay();
        String dateStr = "";
        if (calendar.getSchemeColor() == Constant.MenstrualColor.MENSTRUAL_DAY) {
            dateStr = "月经期";
            dateStr = calculateOrNot(calendar, currentDay, dateStr);
        } else if (calendar.getSchemeColor() == Constant.MenstrualColor.OVULATORY_DAY) {
            dateStr = "排卵期";
            dateStr = calculateOrNot(calendar, currentDay, dateStr);
        } else if (calendar.getSchemeColor() == Constant.MenstrualColor.SAFE_DAY) {
            dateStr = "安全期";
            dateStr = calculateOrNot(calendar, currentDay, dateStr);
        } else if (calendar.getSchemeColor() == Constant.MenstrualColor.CACULATE_MENSTRUAL_DAY) {
            dateStr = "预计月经期";
        } else {
            dateStr = calendar.getYear() + "-" + calendar.getMonth() + "-" + calendar.getDay();
        }
        tvTitle.setText(dateStr);
    }

    private void updateLoveProtectView(DayRecordBean dayRecordBean) {
        if (dayRecordBean != null && dayRecordBean.protects != null) {
            loveProtectAdapter.replace(dayRecordBean.protects);
        } else {
            loveProtectAdapter.clear();
        }
    }

    //更新生活习惯相关的view
    private void updateLivingHabitView(DayRecordBean dayRecordBean) {

        tvEatFruit.setSelected(dayRecordBean.fruit);
        tvEatBreakfast.setSelected(dayRecordBean.breakfast);
        tvTakeExercise.setSelected(dayRecordBean.sports);
        tvDefecate.setSelected(dayRecordBean.defecate);
        tvHotWater.setSelected(dayRecordBean.hot_water);
    }

    //更新生活习惯数据库
    private void updateLivingHabit(TextView textView) {
        if (dayRecordBeans != null && dayRecordBeans.size() >= dayOfMonth) {
            DayRecordBean dayRecordBean = dayRecordBeans.get(dayOfMonth - 1);
            if (textView.getId() == tvHotWater.getId()) {
                dayRecordBean.hot_water = textView.isSelected();
            } else if (textView.getId() == tvDefecate.getId()) {
                dayRecordBean.defecate = textView.isSelected();
            } else if (textView.getId() == tvEatBreakfast.getId()) {
                dayRecordBean.breakfast = textView.isSelected();
            } else if (textView.getId() == tvTakeExercise.getId()) {
                dayRecordBean.sports = textView.isSelected();
            } else if (textView.getId() == tvEatFruit.getId()) {
                dayRecordBean.fruit = textView.isSelected();
            }
            DBUtls.insertDayRecord(dayRecordBean);
            LogUtils.d("db data : ", dayRecordBean);
        } else {
            LogUtils.e("数组下标越界，，找不到对应日期的月经记录");
        }
    }

    private String calculateOrNot(Calendar calendar, int currentDay, String dateStr) {
        if (currentDay < calendar.getDay()) {
            dateStr = "预计" + dateStr;
        }
        return dateStr;
    }

    @Override
    protected int setContentLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == Constant.ConstantCode.REQUEST_MINE) {
            loadDataFromDb();
        }
    }
}
